<?php

namespace Kangcg\Payment;

use Kangcg\Payment\Vendor\WeChat;

/**
 * Class Payment
 * @package Kangcg\Payment
 */
class Payment
{
    /**
     * @param array $config
     * @return PaymentInterface
     */
    public function run(array $config)
    {
        return $this->getPayment($config);
    }

    /**
     * @param array $config
     * @return PaymentInterface
     */
    protected function getPayment(array $config): PaymentInterface
    {
        $config['class'] = $config['class'] ?? 'WeChat';
        $key = md5(json_encode($config, JSON_UNESCAPED_UNICODE));
        if (isset(static::$_install[$key])) {
            return static::$_install[$key];
        }

        $class = 'Kangcg\Payment\Vendor\\' . $config['class'];
        unset($config['class']);
        return static::$_install[$key] = new $class($config);
    }

    /**
     * @param array $config
     * @return WeChat
     */
    public function getWeChat(array $config = [])
    {
        $key = md5(json_encode($config, JSON_UNESCAPED_UNICODE));
        if (isset(static::$_install[$key])) {
            return static::$_install[$key];
        }

        return static::$_install[$key] = new WeChat($config);
    }

    public static function getInstall()
    {
        if (isset(static::$_install['that'])) {
            return static::$_install['that'];
        }

        return static::$_install['that'] = new static();
    }

    protected static $_install = [];
}
